package com.example.springbootwebsockettwo.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: springboot-websocket
 * @description: session容器
 * @author: XianJin.Lu
 * @create: 2021-08-31 15:11
 **/
public class SessionPool {
    public static Map<String, Session>  sessions=new ConcurrentHashMap<>();

    public static void remove(String sessionId) throws IOException {
        for (String userId : sessions.keySet()) {
            Session session = sessions.get(userId);
            if(session.getId().equals(sessionId)){
                sessions.remove(userId);
                break;
            }
        }
    }

    //点对点发送
    public static void sendMessage(String sessionId,String message){
        sessions.get(sessionId).getAsyncRemote().sendText(message);
    }

    //群发
    public static void sendMessage(String message){
        for (String userId : sessions.keySet()) {
            sessions.get(userId).getAsyncRemote().sendText(message);
        }

    }

    public static void sendMessage(Map<String, Object> params) {
        //{"fromuserId":userId,"touserId":touserId,"msg":msg};
     //   String touserId = params.get("touserId").toString();
      //  String msg = params.get("msg").toString();
      //  String fromuserId = params.get("fromuserId").toString();
      //  msg="来自"+fromuserId+"的消息:"+msg;
    //    Session session = sessions.get(touserId);
     //   {"head":{"fromuserId":"1","touserId":"2","msg":"22"},"data":{"lxj":222}}
        String head1 = params.get("head").toString();
        JSONObject headObject = JSON.parseObject(head1);
        String touserId= headObject.get("touserId").toString();
        Session session = sessions.get(touserId);

        String head = JSON.toJSONString(params.get("head"));
        params.get("head");





        if(session!=null){

            //通过指定session消息单发   对象转字符串
           session.getAsyncRemote().sendText(head);


        }
    }
}
